import React, { PureComponent } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Image } from 'react-native';
import screen from '../../common/screen'
import { ScrollView } from 'react-native-gesture-handler';
import color from '../../widget/color';
import Pagination from './HomeMenuPagination'
type Props = {
  menuIcons: Array<Object>,
  onPress: Function
}
type State = {
  currentPage: number
}
class HomeMenuView extends PureComponent<Props, State> {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 0
    }
  }

  render () {
    let { menuIcons, onPress } = this.props

    let menuIconsEle = menuIcons.map((info, index) =>
      <TouchableOpacity key={index} style={styles.box}>
        <Image source={info.icon} style={styles.icon} />
        <Text style={styles.title}> {info.title} </Text>
      </TouchableOpacity>
    )

    // 每页10个，算总页数
    let pageCount = Math.ceil(menuIcons.length / 10)
    // 每10 menu个就用一个view 包裹
    let menuIconsArr = []
    for (let i = 0; i < pageCount; i++) {
      let elePage = menuIconsEle.slice(i * 10, i * 10 + 10)
      menuIconsArr.push(
        <View key={i} style={styles.itemView}>
          {elePage}
        </View>
      )
    }
    return (
      <View style={styles.container}>
        <View style={styles.menuList}>
          <ScrollView
            horizontal  //改横向
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            onScroll={(e) => this.onScroll(e)}
          >
            {menuIconsArr}
          </ScrollView>
        </View>
        <Pagination Length={pageCount} Active={this.state.currentPage} />
      </View >

    );
  }
  onScroll (e: any) {
    let x = e.nativeEvent.contentOffset.x
    let currentPage = Math.round(x / screen.width)
    console.log('onScroll  ' + e.nativeEvent.contentOffset.x + '  page ' + currentPage + '  current ' + this.state.currentPage)

    if (this.state.currentPage != currentPage) {
      this.setState({
        currentPage: currentPage
      })
    }
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffffff",
  },
  menuList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    backgroundColor: "#ffffff",
  },
  box: {
    justifyContent: 'center',  //定义了伸缩项目在主轴线的对齐方式
    alignItems: 'center',//定义项目在交叉轴上如何对齐，可以把其想像成侧轴（垂直于主轴）的“对齐方式”。
    width: screen.width / 5,
    height: screen.width / 5,
  },
  icon: {
    width: screen.width / 9,
    height: screen.width / 9,
    margin: 5
  },
  title: {
    fontSize: 14
  },
  itemView: {
    width: screen.width,
    flexDirection: 'row',
    flexWrap: 'wrap',
  }
})
export default HomeMenuView;